/* Copyright 2007 You may not modify, use, reproduce, or distribute this software except in compliance with the terms of the License at: 
 http://developer.sun.com/berkeley_license.html
 $Id: JMakiWidget.java,v 1.6 2007/11/08 03:24:23 gmurray71 Exp $ 
*/
package jmaki.client;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.HTTPRequest;
import com.google.gwt.user.client.ResponseTextHandler;
import com.google.gwt.core.client.GWT;


/**
 * Base JMakiWidget.
 */
public abstract class JMakiWidget extends Widget {
    
    public static int counter = 0;
    private String moduleName = null;
    private String webRoot = null;
       
    public static String genUuid() {
        return "jmaki_" + counter++;
    };
	
	String uuid = null;
	boolean loaded = false;
	// used if tags are added before the widget is intialized
	
	int height = -1;
	int width = -1;
	String service = null;
	
	Element widget = null;

    public JMakiWidget(int width, int height) {
         this.height = height;
         this.width = width;
         init();      
    }
    
    public JMakiWidget(String service, int width, int height) {
         this.height = height;
         this.width = width; 
         this.service = service;
         init();    
    } 

    public JMakiWidget(String service) {
         this.service = service;
         init();   
    }
    
    public JMakiWidget() {
         init();   
    }
    
    public abstract String getWidgetName();

    class BasicResponseHandler implements ResponseTextHandler {

        JMakiWidget parent;

        BasicResponseHandler(JMakiWidget parent) {
            this.parent = parent;
        }

        public void onCompletion(String txt) {
            parent.postInit(txt);
        }
    }
    
    public void postInit(String template) {

        Element container = DOM.createElement("div");
        DOM.setAttribute(container, "id", uuid + "_container");

        StringBuffer tb = new StringBuffer(template);

        replace(tb, "${uuid}", uuid);

        DOM.appendChild(widget, container);
        DOM.setInnerHTML(container, tb.toString());
        initJS(this, GWT.getModuleBaseURL(), getWidgetName(), uuid, service);

    }
   
    void init() {
        uuid = genUuid();
        widget = DOM.createDiv();

        if (width != -1) {
            DOM.setStyleAttribute(widget, "width", String.valueOf(width));
        }
        if (height != -1) {
            DOM.setStyleAttribute(widget, "height", String.valueOf(height));
        }
        setElement(widget);
        String templateURL =GWT.getModuleBaseURL() + "/resources/" + getWidgetName().replace('.', '/') + "/component.htm";

        HTTPRequest.asyncGet(templateURL,
                new BasicResponseHandler(this));
    }

    public void onLoad() {       
    }
   
    void loadComplete() {
        loaded = true;
     }

    public native void log(String _logStr) /*-{
	    $wnd.alert(_logStr);
    }-*/;

    public native void initJS(JMakiWidget tc, String _webRoot, String _widgetName, String _uuid, String _service) /*-{
        var myservice = undefined;
    	if (_service) myservice = _service;
        $wnd.jmaki.subscribe("/jmaki/runtime/widget/loaded", function(args) {
            if (args.id == _uuid) {
                tc.@jmaki.client.JMakiWidget::loadComplete()();
            }
        });
        var _widgetDir = _webRoot +  "resources/" + _widgetName.replace('.', '/');
        $wnd.jmaki.addWidget({ name : _widgetName, uuid : _uuid, args :{}, service :  myservice, widgetDir : _widgetDir});       
    }-*/;

    public static void replace(StringBuffer buff, String target, String replacement) {
        if (buff == null || target == null || replacement == null) {
            return;
        }
        int index = 0;
        while (index < buff.length()) {
            index = buff.indexOf(target);
            if (index == -1) {
                break;
            }
            buff.replace(index, index + target.length(), replacement);
            index += replacement.length() + 1;
        }
    }
}
